﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Mysoft.MyCM.Web.Controllers.WebApi
{
	/// <summary>
	/// 基础Api控制器，提供来源解析，请求日志记录等功能
	/// </summary>
	[BaseExceptionFilter]
	public class BaseApiController : ApiController
	{
		/// <summary>
		/// 普通构造
		/// </summary>
		public BaseApiController()
			: base()
		{
			// TODO: 增加所需要的AOP扩展内容
		}

		/// <summary>
		/// 重载初始化，以解析来源
		/// </summary>
		/// <param name="controllerContext"></param>
		protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext)
		{
			base.Initialize(controllerContext);
			CalledParams = BaseApiCalledParams.GetParamsFromRequestHeader(controllerContext.Request);
			if (string.IsNullOrEmpty(CalledParams.FromApp)) throw new ArgumentException("未授权的WebApi调用，请联系管理员！");
			if (string.IsNullOrEmpty(CalledParams.FromUser)) throw new ArgumentException("未授权的WebApi调用用户，请联系管理员！");
			// 记录请求日志
			LogInfo("begin");
		}

		#region 日志记录
		/// <summary>
		/// 控制器内快速记录日志，以消息级别
		/// </summary>
		/// <param name="message"></param>
		protected void LogInfo(string message)
		{
			this.writeLog(message, M.MExceptionLevel.Message);
		}
		/// <summary>
		/// 控制器内快速记录日志，以警告级别
		/// </summary>
		/// <param name="message"></param>
		protected void LogWarning(string message)
		{
			this.writeLog(message, M.MExceptionLevel.Warning);
		}
		/// <summary>
		/// 控制器内快速记录日志，以停止级别
		/// </summary>
		/// <param name="message"></param>
		protected void LogStop(string message)
		{
			this.writeLog(message, M.MExceptionLevel.Stop);
		}
		/// <summary>
		/// 控制器内快速记录日志，以致命级别
		/// </summary>
		/// <param name="message"></param>
		protected void LogFatal(string message)
		{
			this.writeLog(message, M.MExceptionLevel.Fatal);
		}
		/// <summary>
		/// 控制器内快速记录日志
		/// </summary>
		/// <param name="message"></param>
		/// <param name="level"></param>
		private void writeLog(string message, M.MExceptionLevel level)
		{
			Business.CMLogger.Log(CalledParams.FromApp, CalledParams.FromUser, CalledParams.FromIP, CalledParams.CalledWebApiVerb, CalledParams.CalledWebApiUrl, message, level);
		}
		#endregion

		/// <summary>
		/// Api调用参数
		/// </summary>
		internal BaseApiCalledParams CalledParams = null;
	}
}